package pl.maslany.angielski;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.StringTokenizer;

public class TestLoader {

	private List<TestRecord> allTests = null;
	
	String urlProp = PropertiesUtil.getProperty("dataURL");
	
	private List<TestRecord> getAllTests() {
		return allTests;
	}
	
	public TestLoader() {
		loadData();
	}
	
	public int remindedTests() {return allTests.size();}
	
	public TestRecord nextTest() {
		if (getAllTests().isEmpty()) {return null;}
		
		TestRecord r = getAllTests().get(0);
		allTests.remove(0);
		return r;
	}
	
	public void loadData() {
		if (allTests == null) {
			allTests = new ArrayList<TestRecord>();
		}
		System.out.println("Loading data!");
		try {
		    // Create a URL for the desired page
			if (urlProp == null) {
				String dataFileName = PropertiesUtil.getProperty("dataFileName");
				
				urlProp = "file:" + System.getProperty("user.dir") + "/" + (dataFileName==null ? "dane.txt" : dataFileName);
				System.out.println(urlProp);
			}
		    URL url = new URL((urlProp));

		    // Read all the text returned by the server
		    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF8"));
		    String str;
		    while ((str = in.readLine()) != null) {
		    	try
		    	{
		    		StringTokenizer t1 = new StringTokenizer(str, ";");
			    	String query = t1.nextToken();
			    	StringTokenizer t2 = new StringTokenizer(t1.nextToken(), "|");
			    	List<String> answers = new ArrayList<String>();
			    	while (t2.hasMoreTokens()) {
			    		answers.add(t2.nextToken());
			    	}
			    	TestRecord r = new TestRecord(query, answers);
			    	allTests.add(r);	
		    	} catch (Exception e)
		    	{
		    		throw new RuntimeException("Incorrect line format (expected: keyToTranslate;correctValue1|correctValue2|correctValue3) - " + str);
		    	}
	    	}
		    in.close();
		    
		    if (PropertiesUtil.shuffle()) {
		    	System.out.println("shuffle data...");
		    	Collections.shuffle(allTests);    	
		    }
		} catch (MalformedURLException e) {
			throw new RuntimeException(e);
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
	}
	
	public static void main (String [] args) {
		new TestLoader();
	}
}
